package com.self.common.aspect;

import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.self.common.exception.BusinessException;
import com.self.common.response.R;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @version v1.0
 * @ClassName: GlobalExceptionHandler
 * @Description:
 * @Author: Mac
 * @Date: 2022/5/29 15:04
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * @Title: api异常处理
     */
    @ExceptionHandler(ApiException.class)
    public R apiHandle(ApiException e){
        if (e.getErrorCode() != null){
            return R.fail(e.getErrorCode());
        }
        return R.fail(e.getMessage());
    }

    /**
     * @Title: 参数校验处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R validateHandle(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()){
            FieldError fieldError = bindingResult.getFieldError();
            return R.fail(fieldError.getField()+":"+fieldError.getDefaultMessage());
        }
        return R.fail(e.getMessage());
    }
    /**
     * @Title: 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public R validateHandle(BusinessException e){
        return R.fail(e.getMessage());
    }

}
